<script setup lang="ts">
import { merge } from 'lodash-es'
import { provide, reactive, ref, shallowRef } from 'vue'

const emit = defineEmits(['confirm', 'close', 'open'])

const formRef = shallowRef()

const visible = ref(false)
const collection = ref<Collection>({
    id: '',
    title: '',
    url: ''
})

const rules = reactive({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    url: [
        { required: true, message: '请输入地址', trigger: 'blur' },
    ]
})

const confirm = async () => {
    await formRef.value?.validate()
    emit('confirm', collection.value)
    close()
}

const close = () => {
    visible.value = false
    emit('close')
}

const open = (data: Collection) => {
    merge(collection.value, data)
    visible.value = true
}

provide('visible', visible)

defineExpose({
    visible,
    confirm,
    close,
    open
})

</script>
<template>
    <el-dialog v-model="visible" :append-to-body="true" draggable @closed="close">
        <template #header>编辑收藏</template>
        <!-- 自定义内容 -->
        <el-form ref="formRef" label-position="top" :model="collection" :rules="rules" style="max-width: 460px"
            status-icon>
            <el-form-item label="标题" prop="title">
                <el-input v-model="collection.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="地址" prop="url">
                <el-input v-model="collection.url" placeholder="请输入地址" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">
                    取消
                </el-button>
                <el-button type="primary" @click="confirm">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style lang="scss" scoped></style>